import { getRequest } from "./api";

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) { // 说明vuex里面有数据
        return;
    }
    // 如果没有数据就走get请求去获取菜单数据并且去格式化，添加，存入
    getRequest("/system/config/menu").then(data => { // 如果不存在state.routes->获取请求
        if (data) {
            //格式化router
            let fmtRouters = formatRoutes(data);
            // 添加到router
            router.addRoutes(fmtRouters);
            //将数据存入vuex
            store.commit('initRoutes', fmtRouters);
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = []; // 空数组
    routes.forEach(router => { //循环拿到里面单独的一个对象
        let {   // 定义单独的对象
            path,
            component,
            name,
            meta,
            iconCls,
            children,
        } = router;
        if (children && children instanceof Array) { // 并且children属于数组
            // 递归
            children = formatRoutes(children);
        }
        let fmRouter = { // 单独对某一个路由格式化
            path: path,
            name: name,
            meta: meta,
            iconCls: iconCls,
            children: children,
            component(resolve) {
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                }
                // 确定组件前三个字母 即可确定在对应哪个包下
                else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter);
    })
    return fmtRoutes;
}